import { setToken, getToken, removeToken } from '@/utils/auth.js'
import { loginForm, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 添加路由信息
  addRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  async login(context, data) {
    const token = await loginForm(data)
    context.commit('setToken', token)
  },

  // 获取用户信息
  async getUserInfoAction(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },

  // 退出登录
  logout(context) {
    // 清除token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('setUserInfo', {})
    // 退出登录 重置路由
    resetRouter()
  }
}

export default {
  namespaced: 'true',
  state,
  mutations,
  actions
}

